package com.xuhuan.practice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhuan.practice.dto.user.UserUpdateInfoDTO;
import com.xuhuan.practice.mapper.UserMapper;
import com.xuhuan.practice.entity.User;
import com.xuhuan.practice.service.UserService;
import com.xuhuan.practice.utils.CurrentUserUtil;
import com.xuhuan.practice.utils.Md5Util;
import java.time.LocalDateTime;
import org.springframework.stereotype.Service;

/**
 * @author: huan.xu
 * @create: 2024/6/10 15:56
 * @description: 用户service接口实现
 **/
@Service
public class UserServiceImpl extends
    ServiceImpl<UserMapper, User> implements UserService {

  /**
   * 根据用户名查询用户
   *
   * @param userName
   * @return
   */
  @Override
  public User getUserByUserName(String userName) {
    LambdaQueryWrapper<User> lambdaQuery = Wrappers.lambdaQuery();
    lambdaQuery.eq(User::getUsername, userName);
    return baseMapper.selectOne(lambdaQuery);
  }

  /**
   * 用户注册
   *
   * @param userName
   * @param password
   */
  @Override
  public void register(String userName, String password) {
    User user = new User();
    user.setUsername(userName);
    user.setPassword(Md5Util.md5String(password));
    user.setCreateTime(LocalDateTime.now());
    user.setUpdateTime(LocalDateTime.now());
    baseMapper.insert(user);
  }

  /**
   * 更新用户
   *
   * @param userUpdateInfoDTO
   */
  @Override
  public void update(UserUpdateInfoDTO userUpdateInfoDTO) {
    User user = baseMapper.selectById(userUpdateInfoDTO.getId());
    user.setNickname(userUpdateInfoDTO.getNickname());
    user.setEmail(userUpdateInfoDTO.getEmail());
    user.setUpdateTime(LocalDateTime.now());
    saveOrUpdate(user);
  }

  /**
   * 更新用户头像
   *
   * @param userPic
   */
  @Override
  public void updateUserPic(String userPic) {
    User queryUser = baseMapper.selectById(CurrentUserUtil.getCurrentUserId());
    queryUser.setUserPic(userPic);
    queryUser.setUpdateTime(LocalDateTime.now());
    saveOrUpdate(queryUser);
  }

  /**
   * 更新密码
   *
   * @param newPwd
   */
  @Override
  public void updatePwd(String newPwd) {
    User queryUser = baseMapper.selectById(CurrentUserUtil.getCurrentUserId());
    queryUser.setPassword(Md5Util.md5String(newPwd));
    queryUser.setUpdateTime(LocalDateTime.now());
    saveOrUpdate(queryUser);
  }
}
